{% extends "layouts/base.html" %}

{% block title %}用户反馈管理 - 近视预防干预系统{% endblock %}

{% block content %}
<main class="main-content-container">
  <div class="feedback-management-content">
    <div class="page-header">
      <h1><i class="bi bi-chat-dots"></i> 用户反馈管理中心</h1>
      <p class="text-muted">查看和处理用户反馈、建议和问题报告</p>
    </div>

    <!-- 筛选器 -->
    <div class="card mb-4">
      <div class="card-body">
        <div class="row g-3">
          <div class="col-md-4">
            <div class="input-group">
              <span class="input-group-text"><i class="bi bi-search"></i></span>
              <input type="text" class="form-control" id="searchInput" placeholder="搜索反馈内容...">
            </div>
          </div>
          <div class="col-md-2">
            <select class="form-select" id="statusFilter">
              <option value="">全部状态</option>
              <option value="pending">待处理</option>
              <option value="processing">处理中</option>
              <option value="resolved">已解决</option>
              <option value="closed">已关闭</option>
            </select>
          </div>
          <div class="col-md-2">
            <select class="form-select" id="priorityFilter">
              <option value="">全部优先级</option>
              <option value="low">低</option>
              <option value="normal">普通</option>
              <option value="high">高</option>
              <option value="urgent">紧急</option>
            </select>
          </div>
          <div class="col-md-2">
            <select class="form-select" id="categoryFilter">
              <option value="">全部分类</option>
              <option value="bug">程序错误</option>
              <option value="feature">功能建议</option>
              <option value="usability">易用性</option>
              <option value="other">其他</option>
            </select>
          </div>
          <div class="col-md-2">
            <button class="btn btn-outline-secondary" id="resetFiltersBtn">
              <i class="bi bi-arrow-clockwise"></i> 重置
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 反馈统计 -->
    <div class="row mb-4">
      <div class="col-md-3">
        <div class="card bg-warning text-white">
          <div class="card-body">
            <div class="d-flex align-items-center">
              <i class="bi bi-clock-history fs-2 me-3"></i>
              <div>
                <h5 class="card-title mb-0" id="pendingCount">0</h5>
                <p class="card-text">待处理</p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="card bg-info text-white">
          <div class="card-body">
            <div class="d-flex align-items-center">
              <i class="bi bi-gear fs-2 me-3"></i>
              <div>
                <h5 class="card-title mb-0" id="processingCount">0</h5>
                <p class="card-text">处理中</p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="card bg-success text-white">
          <div class="card-body">
            <div class="d-flex align-items-center">
              <i class="bi bi-check-circle fs-2 me-3"></i>
              <div>
                <h5 class="card-title mb-0" id="resolvedCount">0</h5>
                <p class="card-text">已解决</p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="card bg-secondary text-white">
          <div class="card-body">
            <div class="d-flex align-items-center">
              <i class="bi bi-archive fs-2 me-3"></i>
              <div>
                <h5 class="card-title mb-0" id="closedCount">0</h5>
                <p class="card-text">已关闭</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 反馈列表 -->
    <div class="card">
      <div class="card-header">
        <h5 class="card-title mb-0">
          <i class="bi bi-list-ul"></i> 反馈列表
        </h5>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table table-hover" id="feedbackTable">
            <thead>
              <tr>
                <th>用户</th>
                <th>反馈内容</th>
                <th>分类</th>
                <th>优先级</th>
                <th>状态</th>
                <th>提交时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <!-- 动态加载内容 -->
            </tbody>
          </table>
        </div>
        
        <!-- 分页器 -->
        <nav aria-label="反馈分页" class="mt-3">
          <ul class="pagination justify-content-center" id="pagination">
            <!-- 动态生成分页 -->
          </ul>
        </nav>
      </div>
    </div>
  </div>
</main>

<!-- 反馈详情模态框 -->
<div class="modal fade" id="feedbackDetailModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">反馈详情</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div id="feedbackDetailContent">
          <!-- 动态加载内容 -->
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
      </div>
    </div>
  </div>
</div>

<!-- 回复反馈模态框 -->
<div class="modal fade" id="replyModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">回复反馈</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <form id="replyForm">
          <div class="mb-3">
            <label for="replyContent" class="form-label">回复内容</label>
            <textarea class="form-control" id="replyContent" rows="4" required></textarea>
          </div>
          <div class="mb-3">
            <label for="newStatus" class="form-label">更新状态</label>
            <select class="form-select" id="newStatus" required>
              <option value="processing">处理中</option>
              <option value="resolved">已解决</option>
              <option value="closed">已关闭</option>
            </select>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" id="sendReplyBtn">发送回复</button>
      </div>
    </div>
  </div>
</div>

<script>
let currentFeedbackId = null;

document.addEventListener('DOMContentLoaded', function() {
    // 初始化页面
    loadFeedback();
    loadFeedbackStats();
    
    // 绑定事件
    document.getElementById('searchInput').addEventListener('input', debounce(searchFeedback, 300));
    document.getElementById('statusFilter').addEventListener('change', searchFeedback);
    document.getElementById('priorityFilter').addEventListener('change', searchFeedback);
    document.getElementById('categoryFilter').addEventListener('change', searchFeedback);
    document.getElementById('resetFiltersBtn').addEventListener('click', resetFilters);
    document.getElementById('sendReplyBtn').addEventListener('click', sendReply);
});

// 加载反馈列表
function loadFeedback(page = 1) {
    const searchTerm = document.getElementById('searchInput').value;
    const statusFilter = document.getElementById('statusFilter').value;
    const priorityFilter = document.getElementById('priorityFilter').value;
    const categoryFilter = document.getElementById('categoryFilter').value;
    
    const params = new URLSearchParams({
        page: page,
        search: searchTerm,
        status: statusFilter,
        priority: priorityFilter,
        category: categoryFilter
    });
    
    AuthManager.authenticatedFetch(`/api/admin/feedback?${params}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderFeedbackTable(data.data.feedback);
                renderPagination(data.data.pagination);
            } else {
                showAlert('加载反馈列表失败: ' + data.message, 'danger');
            }
        })
        .catch(error => {
            showAlert('网络错误，请重试', 'danger');
            console.error('Error:', error);
        });
}

// 加载反馈统计
function loadFeedbackStats() {
    AuthManager.authenticatedFetch('/api/admin/feedback/stats')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('pendingCount').textContent = data.data.pending || 0;
                document.getElementById('processingCount').textContent = data.data.processing || 0;
                document.getElementById('resolvedCount').textContent = data.data.resolved || 0;
                document.getElementById('closedCount').textContent = data.data.closed || 0;
            }
        })
        .catch(error => {
            console.error('Error loading stats:', error);
        });
}

// 渲染反馈表格
function renderFeedbackTable(feedbackList) {
    const tbody = document.querySelector('#feedbackTable tbody');
    tbody.innerHTML = '';
    
    feedbackList.forEach(feedback => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${feedback.user_name || '匿名用户'}</td>
            <td>
                <div class="feedback-content">
                    ${feedback.content.length > 50 ? feedback.content.substring(0, 50) + '...' : feedback.content}
                </div>
            </td>
            <td>
                <span class="badge bg-secondary">${getCategoryText(feedback.category)}</span>
            </td>
            <td>
                <span class="badge bg-${getPriorityColor(feedback.priority)}">${getPriorityText(feedback.priority)}</span>
            </td>
            <td>
                <span class="badge bg-${getStatusColor(feedback.status)}">${getStatusText(feedback.status)}</span>
            </td>
            <td>${formatDate(feedback.created_at)}</td>
            <td>
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-primary" onclick="viewFeedback(${feedback.id})" title="查看详情">
                        <i class="bi bi-eye"></i>
                    </button>
                    <button class="btn btn-outline-success" onclick="replyFeedback(${feedback.id})" title="回复">
                        <i class="bi bi-reply"></i>
                    </button>
                    <button class="btn btn-outline-warning" onclick="updateStatus(${feedback.id})" title="更新状态">
                        <i class="bi bi-arrow-repeat"></i>
                    </button>
                </div>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 工具函数
function getCategoryText(category) {
    const categories = {
        'bug': '程序错误',
        'feature': '功能建议',
        'usability': '易用性',
        'other': '其他'
    };
    return categories[category] || category;
}

function getPriorityText(priority) {
    const priorities = {
        'low': '低',
        'normal': '普通',
        'high': '高',
        'urgent': '紧急'
    };
    return priorities[priority] || priority;
}

function getPriorityColor(priority) {
    const colors = {
        'low': 'secondary',
        'normal': 'primary',
        'high': 'warning',
        'urgent': 'danger'
    };
    return colors[priority] || 'secondary';
}

function getStatusText(status) {
    const statuses = {
        'pending': '待处理',
        'processing': '处理中',
        'resolved': '已解决',
        'closed': '已关闭'
    };
    return statuses[status] || status;
}

function getStatusColor(status) {
    const colors = {
        'pending': 'warning',
        'processing': 'info',
        'resolved': 'success',
        'closed': 'secondary'
    };
    return colors[status] || 'secondary';
}

function viewFeedback(feedbackId) {
    AuthManager.authenticatedFetch(`/api/admin/feedback/${feedbackId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const feedback = data.data;
                document.getElementById('feedbackDetailContent').innerHTML = `
                    <div class="mb-3">
                        <strong>用户：</strong> ${feedback.user_name || '匿名用户'}
                    </div>
                    <div class="mb-3">
                        <strong>分类：</strong> ${getCategoryText(feedback.category)}
                    </div>
                    <div class="mb-3">
                        <strong>优先级：</strong> ${getPriorityText(feedback.priority)}
                    </div>
                    <div class="mb-3">
                        <strong>状态：</strong> ${getStatusText(feedback.status)}
                    </div>
                    <div class="mb-3">
                        <strong>提交时间：</strong> ${formatDate(feedback.created_at)}
                    </div>
                    <div class="mb-3">
                        <strong>反馈内容：</strong>
                        <div class="p-3 bg-light rounded">${feedback.content}</div>
                    </div>
                    ${feedback.replies && feedback.replies.length > 0 ? `
                        <div class="mb-3">
                            <strong>回复记录：</strong>
                            ${feedback.replies.map(reply => `
                                <div class="mt-2 p-3 bg-info bg-opacity-10 rounded">
                                    <div class="mb-1"><strong>${reply.admin_name}</strong> - ${formatDate(reply.created_at)}</div>
                                    <div>${reply.content}</div>
                                </div>
                            `).join('')}
                        </div>
                    ` : ''}
                `;
                new bootstrap.Modal(document.getElementById('feedbackDetailModal')).show();
            } else {
                showAlert('加载反馈详情失败', 'danger');
            }
        })
        .catch(error => {
            showAlert('网络错误，请重试', 'danger');
            console.error('Error:', error);
        });
}

function replyFeedback(feedbackId) {
    currentFeedbackId = feedbackId;
    document.getElementById('replyForm').reset();
    new bootstrap.Modal(document.getElementById('replyModal')).show();
}

function sendReply() {
    if (!currentFeedbackId) return;
    
    const replyData = {
        content: document.getElementById('replyContent').value,
        status: document.getElementById('newStatus').value
    };
    
    AuthManager.authenticatedFetch(`/api/admin/feedback/${currentFeedbackId}/reply`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(replyData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('回复发送成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('replyModal')).hide();
            loadFeedback();
            loadFeedbackStats();
        } else {
            showAlert('发送失败: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        showAlert('网络错误，请重试', 'danger');
        console.error('Error:', error);
    });
}

function resetFilters() {
    document.getElementById('searchInput').value = '';
    document.getElementById('statusFilter').value = '';
    document.getElementById('priorityFilter').value = '';
    document.getElementById('categoryFilter').value = '';
    loadFeedback(1);
}

function searchFeedback() {
    loadFeedback(1);
}

// 其他工具函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

function formatDate(dateString) {
    return new Date(dateString).toLocaleDateString('zh-CN');
}

function showAlert(message, type) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.querySelector('.main-content-container').insertBefore(alertDiv, document.querySelector('.main-content-container').firstChild);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}

function renderPagination(pagination) {
    const paginationElement = document.getElementById('pagination');
    paginationElement.innerHTML = '';
    
    if (pagination.pages <= 1) return;
    
    // 上一页
    const prevItem = document.createElement('li');
    prevItem.className = `page-item ${!pagination.has_prev ? 'disabled' : ''}`;
    prevItem.innerHTML = `<a class="page-link" href="#" onclick="loadFeedback(${pagination.page - 1})">上一页</a>`;
    paginationElement.appendChild(prevItem);
    
    // 页码
    for (let i = 1; i <= pagination.pages; i++) {
        const pageItem = document.createElement('li');
        pageItem.className = `page-item ${i === pagination.page ? 'active' : ''}`;
        pageItem.innerHTML = `<a class="page-link" href="#" onclick="loadFeedback(${i})">${i}</a>`;
        paginationElement.appendChild(pageItem);
    }
    
    // 下一页
    const nextItem = document.createElement('li');
    nextItem.className = `page-item ${!pagination.has_next ? 'disabled' : ''}`;
    nextItem.innerHTML = `<a class="page-link" href="#" onclick="loadFeedback(${pagination.page + 1})">下一页</a>`;
    paginationElement.appendChild(nextItem);
}
</script>
{% endblock %}

